package sfsu.memopad;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/*
 * Login Class that handles getting user name and password to be
 * sent to the server for login.
 */
public class Login extends Activity {
	private EditText userNameBox;
	private EditText passwordBox;
	private Button loginButton;
	private Button cancelButton;
	private String passData;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		setTitle(R.string.login);

		userNameBox = (EditText) findViewById(R.id.userName);
		passwordBox = (EditText) findViewById(R.id.password);

		loginButton = (Button) findViewById(R.id.loginButton);
		cancelButton = (Button) findViewById(R.id.cancelButton);

		cancelButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				storeLoginData("None");
				finish();
			}
		});
		
		loginButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				new NetworkCall().execute(MemoPadActivity.server + "LOGIN<CMD>" + userNameBox.getText().toString() + "<CMD>" + passwordBox.getText().toString());
			}
		});
	}
	
	@Override
	public void onBackPressed() {
		storeLoginData("None");
		finish();
	}
	
	private void storeLoginData(String userName) {
		Intent intent = new Intent();
		intent.putExtra("USERNAME", userName);
		setResult(RESULT_OK, intent);
	}
	
	private void onNetworkResult() {
		if(passData.contentEquals("GOOD")) {
			storeLoginData(userNameBox.getText().toString());
			Toast.makeText(getBaseContext(), userNameBox.getText().toString() + " is logged in.", Toast.LENGTH_LONG).show();			
	        finish();
		}
		else if(passData.contentEquals("BAD")) {
			Toast.makeText(getBaseContext(), "Bad Login.", Toast.LENGTH_LONG).show();
		}
		else if(passData.contentEquals("NEW")) {
			storeLoginData(userNameBox.getText().toString());
			Toast.makeText(getBaseContext(), "New User: " + userNameBox.getText().toString() + "\nCreated.", Toast.LENGTH_LONG).show();
			finish();
		}
	}
	
	public class NetworkCall extends AsyncTask<String, Void, String> {
		 @Override
	        protected void onPreExecute() {
	            Log.i("AsyncTask", "onPreExecute");
		}

		/*
		 * Opens a Http connection to a server.
		 */
		private InputStream OpenHttpConnection(String urlString) throws IOException {
			InputStream in = null;
			int response = -1;

			try {
				URL url = new URL(urlString);
				URLConnection conn = url.openConnection();

				if (!(conn instanceof HttpURLConnection))
					throw new IOException("Not an HTTP connection");
				try {
					HttpURLConnection httpConn = (HttpURLConnection) conn;
					httpConn.setAllowUserInteraction(false);
					httpConn.setInstanceFollowRedirects(true);
					httpConn.setRequestMethod("GET");
					httpConn.connect();
					response = httpConn.getResponseCode();
					if (response == HttpURLConnection.HTTP_OK) {
						in = httpConn.getInputStream();
					}
				} catch (Exception ex) {
					Log.d("Networking", ex.getLocalizedMessage());
					throw new IOException("Error connecting");
				}
			} catch (MalformedURLException e) {
				Log.d("Networking", "Error opening URL: " + e);
			}
			return in;
		}

		/*
		 * Pulls string from server.
		 */
		private String DownloadText(String URL) {
			int BUFFER_SIZE = 2000;
			InputStream in = null;
			try {
				in = OpenHttpConnection(URL);
			} catch (IOException e) {
				Log.d("NetworkingActivity", e.getLocalizedMessage());
				return "";
			}

			InputStreamReader isr = new InputStreamReader(in);
			int charRead;
			String str = "";
			char[] inputBuffer = new char[BUFFER_SIZE];
			try {
				while ((charRead = isr.read(inputBuffer)) > 0) {
					// ---convert the chars to a String---
					String readString = String
							.copyValueOf(inputBuffer, 0, charRead);
					str += readString;
					inputBuffer = new char[BUFFER_SIZE];
				}
				in.close();
			} catch (IOException e) {
				Log.d("NetworkingActivity", e.getLocalizedMessage());
				return "";
			}
			return str;
		}

		// Set up DownloadText as occurs in the background.
		@Override
		protected String doInBackground(String... urls) {
			Log.i("NetworkCall", "doInBackgroup: " + urls);
			return DownloadText(urls[0]);
		}
		
		/*
		 * On completion of Async task, the string pulled from the server is
		 * saved in passData.
		 */
		@Override
		protected void onPostExecute(String result) {
			passData = result;
			onNetworkResult();
		}
	}
}